<?php
namespace app\api\service;
use think\Controller;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/26 0026
 * Time: 15:40
 */

class Category extends Controller {

    /**
     * 获取分类首页数据
     * @return mixed
     */
    public static function get_category_index() {
        if (!$data = cache('category_index')) {
            $data = model('Category')->all(['pid' => 0, 'delete' => 0, 'status' => 1]);
            foreach ($data as $k => $v) {
                $data[$k]['image'] = get_img_url($v['image']);
            }
            cache('category_index', $data);
        }
        return api_return(200, $data);
    }

    /**
     * 根据一级分类ID获取下级分类
     * @param $param
     * @return mixed
     */
    public static function get_category_classify($param) {
        try {
            if (!$data = cache('category_classify_' . $param['id'])) {
                $list = model('Category')->where(['pid' => $param['id'], 'delete' => 0, 'status' => 1])->select();
                if ($list) {
                    foreach ($list as $k => $v) {
                        $classify = model('Category')->where(['pid' => $v['id'], 'delete' => 0, 'status' => 1])->select();
                        foreach ($classify as $key => $val) {
                            $classify[$key]['image'] = get_img_url($val['image']);
                        }
                        $list[$k]['classify'] = $classify;
                    }
                }

                // 获取分类信息
                $cate = model('Category')->get(['id' => $param['id']]);
                $data = ['list' => $list, 'p_cate' => $cate];

                cache('category_classify_' . $param['id'], $data);
            }
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 根据ID获取分类信息
     * @param $param
     * @return mixed
     */
    public static function get_category_info($param) {
        try {
            if (!$data = cache('category_info_' . $param['id'])) {
                $data = model('Category')->get(['id' => $param['id']]);
                cache('category_info_' . $param['id'], $data);
            }
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }
}